package cn.batch.daemon.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.batch.daemon.bean.TaskMissionBean;
import cn.batch.daemon.taskEnum.MissionSts;
import cn.batch.daemon.taskEnum.TaskMissionType;
import cn.batch.daemon.util.JdbcUtils;

import com.skyon.core.config.BaseJNDIEnv;
import com.skyon.core.jdbc.ConnectionProvider;


/**
 * 批量任务数据库操作
 * 
 * @author xihn
 * @version $Revision: 1.1 $
 */
public class MessionTaskStore {
private static Log logger = LogFactory.getLog(MessionTaskStore.class);
    
    private static ConnectionProvider connectionProvider;

    public static void init(){
    	BaseJNDIEnv.init();
    	connectionProvider = new JdbcConnectionOracleProvider();
    }
    
    /**
	 * 更新批量任务的状态。
	 * APP_BATCH_INFO
	 * @return void
	 * @throws SQLException
	 */
	public static void updateTaskMissionStatus(TaskMissionBean tmb) throws SQLException {
		// 判断批次任务是否已有
		List<TaskMissionBean> list = MessionTaskStore.getBatchList(tmb);
		long debugtime = System.currentTimeMillis();
		if (list.size() > 0) {
			TaskMissionBean dbTmb = list.get(0);
			dbTmb.setDisposeEndTm(tmb.getDisposeEndTm() == null ? dbTmb.getDisposeEndTm() : tmb.getDisposeEndTm());
			dbTmb.setMissionSts(tmb.getMissionSts() == null ? dbTmb.getMissionSts() : tmb.getMissionSts());
			dbTmb.setRemark(tmb.getRemark() == null ? dbTmb.getRemark() : tmb.getRemark());
			dbTmb.setMissionTyp(tmb.getMissionTyp() == null? dbTmb.getMissionTyp() : tmb.getMissionTyp());
			updateImportDay(dbTmb);  // 如果有就更新
			logger.debug("判断批次任务是否已有（更新花费时间）:"+(System.currentTimeMillis()-debugtime));
		} else {
			insertMession(tmb); // 如果没有就插入
			logger.debug("判断批次任务是否已有（如果没有插入花费时间）:"+(System.currentTimeMillis()-debugtime));
		}
		return ;
	}
    
    /**
     * 新增批量任务处理状态信息
     * @param TaskMissionBean
     * 
     * @return int 
     * @throws Exception 
     */
	public static int insertMession(TaskMissionBean task) throws SQLException{
		init();
		int result = 0;
        Connection connection = null;
        Statement statement = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String sT = sdf.format(task.getDisposeStartTm());
        //String eT = sdf.format(task.getDisposeEndTm());
        String sql = "insert into APP_BATCH_INFO (ID,BATCH_NO,BATCH_TYPE,BATCH_STAUT,BATCH_START,REMARK) " 
        	+ "values (S_TASK_MISSION_ID.nextval,'"+task.getBatch_no()+"','"+task.getMissionTyp().getValue()+"','"+task.getMissionSts().getValue()+"'," 
        	+ " to_date('"+sT+"','yyyy-mm-dd hh24:mi:ss'),'"+task.getRemark()+"')";
        //System.out.println(sql);
        try{
            connection = connectionProvider.getConnection();
            statement = connection.createStatement();
            result = statement.executeUpdate(sql);
        }catch(SQLException e){
            connection.rollback();
            logger.error("新增批量任务处理状态信息出错 INSERT SQL:" + sql, e);
            e.printStackTrace();
            throw e;
        }finally{
        	JdbcUtils.closeStatement(statement);
        	JdbcUtils.closeConnection(connection);
        }
        return result;
	}
	/**
     * 判断批量任务处理状态信息是否已有
     * @param TaskMissionBean
     * 
     * @return int 
     * @throws Exception 
     */
	public static List<TaskMissionBean> getBatchList(TaskMissionBean bean)throws SQLException{
		init();
		ResultSet rs = null;
		List<TaskMissionBean> listtmb = new ArrayList<TaskMissionBean>();
        Connection connection = null;
        Statement statement = null;
        if (bean != null) {
	        String sql = "SELECT ID,BATCH_NO,BATCH_TYPE,BATCH_STAUT,BATCH_START,BATCH_END,REMARK FROM APP_BATCH_INFO WHERE BATCH_NO = '"+bean.getBatch_no()+"' and BATCH_TYPE = '"+bean.getMissionTyp().getValue()+"'";
	        try{
	            connection = connectionProvider.getConnection();
	            statement = connection.createStatement();
	            rs =  statement.executeQuery(sql);
	            while(rs.next()){
	            	TaskMissionBean tmb = new TaskMissionBean();
	            	if(rs.getString(1) != null)
	            	{
	            		tmb.setId(rs.getInt(1));
	            	}
	            	if(rs.getString(2) != null)
	            	{
	            		tmb.setBatch_no(rs.getString(2));
	            	}
	            	if(rs.getString(3) != null)
	            	{
	            		tmb.setMissionTyp(TaskMissionType.fromString(rs.getString(3)));
	            	}
	            	if(rs.getString(4) != null)
	            	{
	            		tmb.setMissionSts(MissionSts.fromString(rs.getString(4)));
	            	}
	            	if(rs.getString(5) != null)
	            	{
	            		tmb.setDisposeStartTm(rs.getTimestamp(5));
	            	}
	            	if(rs.getString(6) != null)
	            	{
	            		tmb.setDisposeEndTm(rs.getTimestamp(6));
	            	}
	            	if(rs.getString(7) != null && !rs.getString(7).trim().equals("null"))
	            	{
	            		tmb.setRemark(rs.getString(7));
	            	}
	            	listtmb.add(tmb);
	            }
	        }catch(SQLException e){
	            //connection.rollback();
	            logger.error("查询批量任务处理信息出错 ERROR SQL:" + sql, e);
	            e.printStackTrace();
	            throw e;
	        }finally{
	        	JdbcUtils.closeStatement(statement);
	        	JdbcUtils.closeConnection(connection);
	        }
        }
        return listtmb;
	}
	
	/**
     * 修改批量任务处理状态
     * 
     * @param TaskMissionBean
     *        
     * @return int
	 * @throws SQLException 
     * @throws Exception 
     */
	public static int updateImportDay(TaskMissionBean bean) throws SQLException {
		init();
        int result = 0;
        Connection connection = null;
        Statement statement = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        
        String sql = "UPDATE APP_BATCH_INFO SET BATCH_STAUT ='"+bean.getMissionSts().getValue()+"' " 
        		+",REMARK='"+bean.getRemark()+"'";
        if(bean.getDisposeEndTm() != null)
        {
        	String eT = sdf.format(bean.getDisposeEndTm());
        	sql+=",BATCH_END = to_date('"+eT+"','yyyy-mm-dd hh24:mi:ss') ";
        }
        if(bean.getDisposeStartTm() != null)
        {
        	String sT = sdf.format(bean.getDisposeStartTm());
        	sql+=",BATCH_START = to_date('"+sT+"','yyyy-mm-dd hh24:mi:ss') ";
        }
        sql +=" WHERE BATCH_NO='" + bean.getBatch_no() + "' and BATCH_TYPE = '"+bean.getMissionTyp().getValue()+"'";;
        
        connection = connectionProvider.getConnection();
        try {
             statement = connection.createStatement();
             result = statement.executeUpdate(sql);
            } catch (SQLException sqle) {
              connection.rollback();
              logger.error("修改批量任务处理状态出错  UPDATE SQL:" + sql, sqle);
              sqle.printStackTrace();
              throw sqle;
            }finally{
            	JdbcUtils.closeStatement(statement);
            	JdbcUtils.closeConnection(connection);
            }
        return result;
	}
	
}
